package org.jeecg.modules.gis.util.network;

import org.geotools.graph.build.line.LineStringGraphGenerator;
import org.geotools.graph.structure.Graph;
import org.geotools.graph.build.feature.FeatureGraphGenerator;
import org.geotools.geojson.feature.FeatureJSON;
import org.jeecg.modules.gis.entity.GisRoadNetworkEx;
import org.jeecg.modules.gis.util.GeoJsonJavaBeanUtil;
import org.locationtech.jts.geom.*;
import com.alibaba.fastjson.JSONObject;
import org.opengis.feature.simple.SimpleFeature;

import java.io.StringReader;
import java.util.List;

public class NetWorkUtil {

    public static Graph buildGraph(List<GisRoadNetworkEx> net) throws Exception {
        FeatureGraphGenerator generator = new FeatureGraphGenerator(new LineStringGraphGenerator());
        FeatureJSON fjson = new FeatureJSON();

        for (GisRoadNetworkEx ex : net) {
            JSONObject json = GeoJsonJavaBeanUtil.beanToFeature(ex);
            SimpleFeature feature = fjson.readFeature(new StringReader(json.toJSONString()));
            generator.add(feature);
        }
        return generator.getGraph();
    }

    public static Coordinate findNearestPoint(LineString line, Coordinate coord) {
        Coordinate[] coords = line.getCoordinates();
        Coordinate nearest = null;
        double minDistance = Double.MAX_VALUE;

        for (int i = 0; i < coords.length - 1; i++) {
            Coordinate c1 = coords[i];
            Coordinate c2 = coords[i + 1];
            Coordinate candidate = closestPointOnSegment(coord, c1, c2);
            double dist = candidate.distance(coord);
            if (dist < minDistance) {
                minDistance = dist;
                nearest = candidate;
            }
        }
        return nearest;
    }

    // 工具方法：计算点到线段最近点
    private static Coordinate closestPointOnSegment(Coordinate p, Coordinate a, Coordinate b) {
        double dx = b.x - a.x;
        double dy = b.y - a.y;
        double lengthSquared = dx * dx + dy * dy;
        if (lengthSquared == 0) return a;

        double t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / lengthSquared;
        t = Math.max(0, Math.min(1, t));
        return new Coordinate(a.x + t * dx, a.y + t * dy);
    }
}
